<script lang="ts" name="syssalesreturnorderDetail" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { formatDate } from '/@/utils/formatTime';
import { useSyssalesreturnorderApi } from '/@/api/order/syssalesreturnorder';
import { useSysOrgApi } from '/@/api/system/sysOrg';
import { useSysUserApi } from '/@/api/system/sysUser';

//父级传递来的函数，用于回调
const emit = defineEmits(["reloadTable"]);
const syssalesreturnorderApi = useSyssalesreturnorderApi();
const sysOrgApi = useSysOrgApi();
const sysUserApi = useSysUserApi();

const state = reactive({
	title: '',
	loading: false,
	showDialog: false,
	ruleForm: {} as any,
	stores: {},
	dropdownData: {} as any,
	// 下拉框数据
	orgList: [] as any[],
	userList: [] as any[],
});

// 根据ID获取机构名称
const getOrgName = (orgId: number) => {
	const org = state.orgList.find(item => item.id === orgId);
	return org ? org.name : orgId;
};

// 根据ID获取用户名称
const getUserName = (userId: number) => {
	const user = state.userList.find(item => item.id === userId);
	return user ? user.realName : userId;
};

// 根据状态值获取中文描述
const getStatusText = (status: any) => {
	const statusMap: { [key: string]: string } = {
		'1': '草稿',
		'2': '待审核', 
		'3': '驳回',
		'4': '未出库',
		'5': '部分出库',
		'6': '已完成',
		'7': '已关闭',
		'Draft': '草稿',
		'PendingReview': '待审核',
		'Rejected': '驳回',
		'NotOutOfWarehouse': '未出库',
		'PartiallyOutOfWarehouse': '部分出库',
		'Completed': '已完成',
		'Closed': '已关闭'
	};
	return statusMap[status] || status;
};

// 根据状态值获取标签类型
const getStatusType = (status: any) => {
	const statusTypeMap: { [key: string]: string } = {
		'1': 'info',
		'2': 'warning',
		'3': 'danger',
		'4': 'warning',
		'5': 'warning',
		'6': 'success',
		'7': 'info',
		'Draft': 'info',
		'PendingReview': 'warning',
		'Rejected': 'danger',
		'NotOutOfWarehouse': 'warning',
		'PartiallyOutOfWarehouse': 'warning',
		'Completed': 'success',
		'Closed': 'info'
	};
	return statusTypeMap[status] || 'info';
};

// 打开对话框
const openDialog = async (row: any, title: string) => {
	state.title = title;
	state.showDialog = true;
	state.loading = true;
	
	try {
		// 加载机构列表
		const orgRes = await sysOrgApi.getList();
		state.orgList = orgRes.data.result || [];
		
		// 加载用户列表
		const userRes = await sysUserApi.getList();
		state.userList = userRes.data.result || [];
		
		// 如果有传入数据，则从服务器获取完整详情
		if (row && row.id) {
			const detailRes = await syssalesreturnorderApi.detail(row.id);
			state.ruleForm = detailRes.data.result || {};
		} else {
			state.ruleForm = { ...row };
		}
	} catch (error) {
		console.error('加载数据失败:', error);
		ElMessage.error('加载数据失败');
	} finally {
		state.loading = false;
	}
};

// 关闭对话框
const closeDialog = () => {
	state.showDialog = false;
	state.ruleForm = {};
};

// 复制操作
const handleCopy = () => {
	// 复制到剪贴板
	navigator.clipboard.writeText(state.ruleForm.code).then(() => {
		ElMessage.success('单号已复制到剪贴板');
	}).catch(() => {
		ElMessage.error('复制失败');
	});
};

// 打印操作
const handlePrint = () => {
	// 创建打印内容
	const printContent = `
		<!DOCTYPE html>
		<html>
		<head>
			<meta charset="utf-8">
			<title>销售退货订单详情 - ${state.ruleForm.code}</title>
			<style>
				body { font-family: Arial, sans-serif; margin: 20px; }
				.header { text-align: center; margin-bottom: 30px; }
				.header h1 { color: #333; margin: 0; }
				.header h2 { color: #666; margin: 10px 0; }
				.info-table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
				.info-table td { padding: 8px 12px; border: 1px solid #ddd; }
				.info-table .label { background-color: #f5f5f5; font-weight: bold; width: 120px; }
				.status { text-align: right; margin-top: 20px; }
				.status-tag { padding: 4px 8px; border-radius: 4px; font-weight: bold; }
				.status-draft { background-color: #e1f5fe; color: #0277bd; }
				.status-pending { background-color: #fff3e0; color: #f57c00; }
				.status-rejected { background-color: #ffebee; color: #c62828; }
				.status-completed { background-color: #e8f5e8; color: #2e7d32; }
				.status-closed { background-color: #e1f5fe; color: #0277bd; }
				@media print {
					body { margin: 0; }
					.header { page-break-after: avoid; }
				}
			</style>
		</head>
		<body>
			<div class="header">
				<h1>销售退货订单详情</h1>
				<h2>单号：${state.ruleForm.code}</h2>
			</div>
			
			<table class="info-table">
				<tr>
					<td class="label">制单人</td>
					<td>${state.ruleForm.createUserName || getUserName(state.ruleForm.createUserId)}</td>
					<td class="label">所在部门</td>
					<td>${getOrgName(state.ruleForm.salesDeptId)}</td>
				</tr>
				<tr>
					<td class="label">制单时间</td>
					<td>${formatDate(state.ruleForm.createTime, 'YYYY-mm-dd HH:MM:SS') || '无'}</td>
					<td class="label">退货日期</td>
					<td>${formatDate(state.ruleForm.returnDate, 'YYYY-mm-dd') || '无'}</td>
				</tr>
				<tr>
					<td class="label">客户名称</td>
					<td>${state.ruleForm.customerName}</td>
					<td class="label">联系人</td>
					<td>${state.ruleForm.contactPerson}</td>
				</tr>
				<tr>
					<td class="label">联系方式</td>
					<td>${state.ruleForm.contactMethod}</td>
					<td class="label">销售部门</td>
					<td>${getOrgName(state.ruleForm.salesDeptId)}</td>
				</tr>
				<tr>
					<td class="label">销售负责人</td>
					<td>${getUserName(state.ruleForm.salesManagerId)}</td>
					<td class="label">销售单号</td>
					<td>${state.ruleForm.salesOrderNumber}</td>
				</tr>
				<tr>
					<td class="label">退货原因</td>
					<td colspan="3">${state.ruleForm.returnReason}</td>
				</tr>
				<tr>
					<td class="label">备注</td>
					<td colspan="3">${state.ruleForm.remark || '无'}</td>
				</tr>
			</table>
			
			<div class="status">
				<span style="color: #909399; font-size: 14px;">单据状态：</span>
				<span class="status-tag status-${getStatusType(state.ruleForm.documentStatus)}">
					${getStatusText(state.ruleForm.documentStatus)}
				</span>
			</div>
		</body>
		</html>
	`;
	
	// 打开新窗口进行打印
	const printWindow = window.open('', '_blank');
	printWindow.document.write(printContent);
	printWindow.document.close();
	
	// 等待内容加载完成后打印
	printWindow.onload = () => {
		printWindow.print();
		printWindow.close();
	};
};

// 编辑操作
const handleEdit = () => {
	// 触发父组件的编辑功能
	emit('edit', state.ruleForm);
	closeDialog();
};

// 暴露方法给父组件
defineExpose({
	openDialog,
	closeDialog
});
</script>

<template>
	<div class="syssalesreturnorder-detail-container">
		<el-dialog v-model="state.showDialog" :width="900" draggable :close-on-click-modal="false" :show-close="false">
			<template #header>
				<div style="color: #fff; display: flex; justify-content: space-between; align-items: center;">
					<span>{{ state.title }}</span>
					<el-button type="danger" size="small" @click="closeDialog" icon="ele-Close">关闭</el-button>
				</div>
			</template>
			
			<div v-loading="state.loading" style="min-height: 400px;">
				<!-- 订单头部信息 -->
				<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding: 15px; background: #f5f7fa; border-radius: 8px;">
					<div style="display: flex; align-items: center;">
						<h3 style="margin: 0; color: #303133;">销售退货单号: {{ state.ruleForm.code }}</h3>
						<el-button type="text" size="small" @click="handleCopy" style="margin-left: 10px;" icon="ele-CopyDocument">复制</el-button>
					</div>
					<div style="display: flex; gap: 8px;">
						<el-button type="primary" size="small" @click="handleEdit" icon="ele-Edit">编辑</el-button>
						<el-button type="info" size="small" @click="handleCopy" icon="ele-CopyDocument">复制</el-button>
						<el-button type="warning" size="small" @click="handlePrint" icon="ele-Printer">打印</el-button>
					</div>
				</div>

				<!-- 订单详情信息 -->
				<el-card shadow="never" style="border: 1px solid #e4e7ed;">
					<el-row :gutter="20">
						<!-- 第一行 -->
						<el-col :span="8">
							<div style="margin-bottom: 15px;">
								<span style="color: #909399; font-size: 14px;">制单人:</span>
								<span style="margin-left: 8px; color: #303133; font-weight: 500;">{{ state.ruleForm.createUserName || getUserName(state.ruleForm.createUserId) }}</span>
							</div>
						</el-col>
						<el-col :span="8">
							<div style="margin-bottom: 15px;">
								<span style="color: #909399; font-size: 14px;">所在部门:</span>
								<span style="margin-left: 8px; color: #303133; font-weight: 500;">{{ getOrgName(state.ruleForm.salesDeptId) }}</span>
							</div>
						</el-col>
						<el-col :span="8">
							<div style="margin-bottom: 15px;">
								<span style="color: #909399; font-size: 14px;">制单时间:</span>
								<span style="margin-left: 8px; color: #303133; font-weight: 500;">{{ formatDate(state.ruleForm.createTime, 'YYYY-mm-dd HH:MM:SS') || '无' }}</span>
							</div>
						</el-col>
						
						<!-- 第二行 -->
						<el-col :span="8">
							<div style="margin-bottom: 15px;">
								<span style="color: #909399; font-size: 14px;">退货日期:</span>
								<span style="margin-left: 8px; color: #303133; font-weight: 500;">{{ formatDate(state.ruleForm.returnDate, 'YYYY-mm-dd') || '无' }}</span>
							</div>
						</el-col>
						<el-col :span="8">
							<div style="margin-bottom: 15px;">
								<span style="color: #909399; font-size: 14px;">客户名称:</span>
								<span style="margin-left: 8px; color: #303133; font-weight: 500;">{{ state.ruleForm.customerName }}</span>
							</div>
						</el-col>
						<el-col :span="8">
							<div style="margin-bottom: 15px;">
								<span style="color: #909399; font-size: 14px;">联系人:</span>
								<span style="margin-left: 8px; color: #303133; font-weight: 500;">{{ state.ruleForm.contactPerson }}</span>
							</div>
						</el-col>
						
						<!-- 第三行 -->
						<el-col :span="8">
							<div style="margin-bottom: 15px;">
								<span style="color: #909399; font-size: 14px;">联系方式:</span>
								<span style="margin-left: 8px; color: #303133; font-weight: 500;">{{ state.ruleForm.contactMethod }}</span>
							</div>
						</el-col>
						<el-col :span="8">
							<div style="margin-bottom: 15px;">
								<span style="color: #909399; font-size: 14px;">销售部门:</span>
								<span style="margin-left: 8px; color: #303133; font-weight: 500;">{{ getOrgName(state.ruleForm.salesDeptId) }}</span>
							</div>
						</el-col>
						<el-col :span="8">
							<div style="margin-bottom: 15px;">
								<span style="color: #909399; font-size: 14px;">销售负责人:</span>
								<span style="margin-left: 8px; color: #303133; font-weight: 500;">{{ getUserName(state.ruleForm.salesManagerId) }}</span>
							</div>
						</el-col>
						
						<!-- 第四行 -->
						<el-col :span="8">
							<div style="margin-bottom: 15px;">
								<span style="color: #909399; font-size: 14px;">销售单号:</span>
								<span style="margin-left: 8px; color: #303133; font-weight: 500;">{{ state.ruleForm.salesOrderNumber }}</span>
							</div>
						</el-col>
						<el-col :span="8">
							<div style="margin-bottom: 15px;">
								<span style="color: #909399; font-size: 14px;">退货原因:</span>
								<span style="margin-left: 8px; color: #303133; font-weight: 500;">{{ state.ruleForm.returnReason }}</span>
							</div>
						</el-col>
						<el-col :span="8">
							<div style="margin-bottom: 15px;">
								<span style="color: #909399; font-size: 14px;">备注:</span>
								<span style="margin-left: 8px; color: #303133; font-weight: 500;">{{ state.ruleForm.remark || '无' }}</span>
							</div>
						</el-col>
					</el-row>
					
					<!-- 单据状态 -->
					<div style="text-align: right; margin-top: 20px; padding-top: 15px; border-top: 1px solid #e4e7ed;">
						<span style="color: #909399; font-size: 14px;">单据状态:</span>
						<el-tag 
							:type="getStatusType(state.ruleForm.documentStatus)"
							style="margin-left: 8px; font-weight: 500;">
							{{ getStatusText(state.ruleForm.documentStatus) }}
						</el-tag>
					</div>
				</el-card>
			</div>
		</el-dialog>
	</div>
</template>

<style scoped>
.syssalesreturnorder-detail-container {
	/* 样式可以在这里添加 */
}

:deep(.el-dialog__header) {
	background: #409eff;
	padding: 15px 20px;
}

:deep(.el-dialog__body) {
	padding: 20px;
}
</style>
